package com.zjb.demo.common.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.mybatisflex.core.paginate.Page;
import com.zjb.demo.common.domain.dto.SysLoginInfo;
import com.zjb.demo.common.domain.response.AjaxResult;
import com.zjb.demo.system.domain.query.SysLoginInfoPageQuery;
import com.zjb.demo.system.service.SysLoginInfoService;
import com.zjb.demo.system.service.SysPasswordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * 系统日志
 *
 * @author 庄佳彬
 * @since 2023/12/24 22:12
 */
@Controller
@Api(tags = "系统日志")
@Mapping("/monitor/logininfor")
public class SysLoginInfoController {

    @Inject
    private SysLoginInfoService sysLoginInfoService;

    @Inject
    private SysPasswordService sysPasswordService;

    @Get
    @Mapping("/list")
    @ApiOperation(value = "日志列表")
    public AjaxResult<Page<SysLoginInfo>> list(SysLoginInfoPageQuery query) {
        return AjaxResult.success(sysLoginInfoService.pageList(query));
    }

    @Get
    @Mapping("/export")
    @ApiOperation(value = "日志导出")
    public void export(SysLoginInfoPageQuery query) throws IOException {
        var list = sysLoginInfoService.list(query);
        var ctx = Context.current();
        ctx.contentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        ctx.headerAdd("Content-Disposition", "attachment;filename=" + URLEncoder.encode("登录日志", StandardCharsets.UTF_8) + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx");
        var os = ctx.outputStream();
        EasyExcel.write(os, SysLoginInfo.class)
                .sheet("登录日志")
                .doWrite(list);
    }

    @Delete
    @Mapping("/{infoIds}")
    @ApiOperation(value = "删除日志")
    public AjaxResult<Boolean> delete(Long[] infoIds) {
        return AjaxResult.success(sysLoginInfoService.removeByIds(List.of(infoIds)));
    }

    @Delete
    @Mapping("/clean")
    @ApiOperation(value = "清除日志")
    public AjaxResult<Void> clean() {
        sysLoginInfoService.clean();
        return AjaxResult.success();
    }

    @Get
    @Mapping("/unlock/{userName}")
    @ApiOperation(value = "解锁用户")
    public AjaxResult<Void> unlock(String userName) {
        sysPasswordService.cleanLoginRecordCache(userName);
        return AjaxResult.success();
    }
}
